<template>
  <el-row>
    <el-col :span="24">
      <payment-header :orderDetail="orderDetail"></payment-header>
      <goods :orderDetail="orderDetail"></goods>
      <Portlet title="师傅报价" :show-title="false">
        <table class="table show-table">
          <tr>
            <td width="40%">
              <table>
                <tr>
                  <td width="130">
                    <div>
                      <img style="no-repeat: center; border:1px solid grey; height: 102px; width: 102px; border-radius: 50% !important;" :src="fhbOrderBiddingLog.businessImg ? ('/api/ms-mongodb/file/download?fileId=' + fhbOrderBiddingLog.businessImg) : 'http://www.placehold.it/200x148/EFEFEF/AAAAAA&amp;'"  alt="">
                    </div>
                  </td>
                  <td width="800">
                    <div style="height: 150px; margin: 15px 15px 15px 0px; ">
                      <span style="font-size: 16px; font-color: #1F2D3D">{{fhbOrderBiddingLog.name}}</span>
                      <el-tooltip v-if="fhbOrderBiddingLog.isAuthention == 1" class="item" effect="dark" content="已通过实名认证" placement="top-start">
                        <img style="no-repeat: center; height: 16px; width: 20px" src="/static/images/faHuoBao/certification.png" alt="实名认证" title="已通过实名认证" />
                      </el-tooltip>
                      <el-tooltip v-if="fhbOrderBiddingLog.isAuthention !== 1" class="item" effect="dark" content="未实名认证" placement="top-start">
                        <img style="no-repeat: center; height: 16px; width: 20px" src="/static/images/faHuoBao/Unproven.png" alt="未实名认证" title="未实名认证" />
                      </el-tooltip>

                      <el-tooltip class="item" effect="dark" :content="carContent" placement="top-start" style="margin-top: 5px">
                        <img style="no-repeat: center; height: 14px; width: 20px" src="/static/images/faHuoBao/car.png" alt="车辆" :title="carContent" />
                      </el-tooltip>
                      <el-tooltip class="item" effect="dark" :content="areaContent" placement="top-start">
                        <img style="no-repeat: center; height: 16px; width: 20px" src="/static/images/faHuoBao/warehouse.png" alt="仓库" :title="areaContent" />
                      </el-tooltip>

                      <br />
                      <span>{{fhbOrderBiddingLog.nature}}</span><span v-if="fhbOrderBiddingLog.address"> | {{fhbOrderBiddingLog.address}} </span>
                      <br>
                      <div class="bottom">
                        <el-tooltip v-if="fhbOrderBiddingLog.favorTMJD == 1" class="item" effect="dark" content="支持汪师傅核销" placement="right">
                          <img style="no-repeat: center; height: 22px; width: 46px" src="/static/images/faHuoBao/wangshifu.png" alt="汪师傅" title="支持汪师傅核销" />
                        </el-tooltip>
                        <el-tooltip v-if="fhbOrderBiddingLog.favorTMJD == 1" class="item" effect="dark" content="支持喵师傅核销" placement="right">
                          <img style="no-repeat: center; height: 22px; width: 46px" src="/static/images/faHuoBao/miaoshifu.png" alt="喵师傅" title="支持喵师傅核销" />
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="服务承诺" placement="right">
                          <img style="no-repeat: center; height: 22px; width: 61px" src="/static/images/faHuoBao/ServiceCommitment.png" alt="服务承诺" title="服务承诺"  @click="pledge($event, fhbOrder)"/>
                        </el-tooltip>
                      </div>
                      <br>
                      <span style="color: gray">服务确认码：{{fhbOrder.serviceCode}}</span>
                      <br>
                      <span>好评率：{{fhbOrderBiddingLog.evalueGoods}}%</span><span style="margin-left: 20px;">总单数：{{fhbOrderBiddingLog.orderSucessCount}}</span><span style="margin-left: 20px;">投诉数：{{fhbOrderBiddingLog.complaintCount}}</span>
                    </div>
                  </td>
                </tr>
              </table>
            </td>
            <td width="10%">
            </td>
            <td width="50%">
              <div style="margin: 10px 0px 0px 0px">
                <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="费用名称" prop="additionalName">
                        <el-input v-model="form.additionalName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="追加金额" prop="additionalMoney">
                        <el-input v-model="form.additionalMoney">
                          <template slot="append">元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="追加说明" prop="additionalMemo">
                        <el-input type="textarea" v-model="form.additionalMemo"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </td>
          </tr>
        </table>
      </Portlet>
      <Portlet title="支付方式" :show-title="true">
        <el-form>
          <el-col :span="24" style="text-align: center; border-bottom: 1px dashed #C0CCDA;">
            <el-form-item
              prop="paymentType"
            >
              <el-radio-group v-model="model.paymentType">
                <el-tooltip :key="index"  v-for="(item, index) in computedPaymentTypes" :disabled="!item.tip" :content='item.tip'>
                  <el-radio-button :label="item.value" :disabled="item.disabled">
                    {{item.text}}
                  </el-radio-button>
                </el-tooltip>
              </el-radio-group>
              <p>余额：{{balance | decimalNumFilter}} 元</p>
            </el-form-item>
          </el-col>
        </el-form>
        <el-col :span="24" style="text-align: center; margin-top: 15px;">
          <p>总计：{{form.additionalMoney}}元</p>
          <el-button type="button" class="btn btn-primary btn-lg green ladda-button" data-style="zoom-out" @click="paymentDialog()">追加支付</el-button>
        </el-col>
        <div class="clearfix"></div>
      </Portlet>
    </el-col>
    <el-dialog
      title="温馨提示"
      :visible.sync="paymentState"
      width="30%"
      center
    >
      <div style="text-align:center">恭喜您支付成功！本页面即将在3秒后跳转{{routeName === 'myOrdersInservicePaymentAdditional' ? '服务中' : '待确认'}}列表</div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="btnDialog">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="温馨提示"
      :visible.sync="payDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="30%"
      center
    >
      <div style="text-align:center" v-if="!disabledBtn">请您在新打开的页面完成支付?</div>
      <div style="text-align:center" v-if="disabledBtn">
        <b style="font-size: 16px;">订单支付状态暂时无法确认</b>
        <p>尊敬的客户你好，很抱歉我们暂时无法确认您的支付结果,<br>
          建议您等待五分钟后再查看支付结果</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!disabledBtn" @click="unsuccessful">支付遇到问题</el-button>
        <el-button type="primary" v-if="!disabledBtn" @click="successful" :disabled="disabledBtn">{{ disabledBtn ? '等待支付结果' : '已经完成支付' }}</el-button>
        <el-button type="primary" v-if="disabledBtn" @click="btnDialog"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="支付确认"
      :visible.sync="confirmPayDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="40%"
      center
    >
      <div style="text-align:center; width: 100%; height: 100%;">
        <table class="table table-hover table-bordered table-striped table-text-center">
          <tr>
            <td colspan="4" align="left"><span style="font-weight: 600">订单信息</span></td>
          </tr>
          <tr>
            <td width="100px">订单号</td>
            <td align="left">{{confirmHtml.orderNo}}</td>
            <td width="100px">服务类型</td>
            <td align="left">{{confirmHtml.service}}</td>
          </tr>
          <tr>
            <td>收件人</td><td align="left">{{confirmHtml.consigneName}}</td><td>收件电话</td><td align="left">{{confirmHtml.consignePhone}}</td>
          </tr>
          <tr>
            <td>服务师傅</td><td colspan="3" align="left">{{confirmHtml.name}}</td>
          </tr>
          <tr>
            <td colspan="4" align="left"><span style="font-weight: 600">追加信息</span></td>
          </tr>
          <tr>
            <td>费用名称</td><td align="left">{{confirmHtml.additionalName}}</td><td>追加金额</td><td align="left">{{confirmHtml.additionalMoney}}元 </td>
          </tr>
          <tr>
            <td>追加备注</td><td colspan="3" align="left"><div>{{confirmHtml.additionalMemo}}</div></td>
          </tr>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmPayDialog = false">取消支付</el-button>
        <el-button type="primary" @click="payment($event)">确认支付</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="钱包密码"
      :visible.sync="showWalletPay"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="20%"
      center
    >
      <div style="text-align: center">
        <el-input v-model="walletPwd" type="password" :maxlength="6" />
        <span class="font-red">{{error_message}}</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showWalletPay = false">取 消</el-button>
        <el-button type="primary" @click="walletpay" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
    <div v-html="htmltext"></div>
  </el-row>
</template>
<script>
import paymentHeader from '@/views/fhb/myOrders/components/detail/paymentHeader'
import goods from '@/views/fhb/myOrders/components/detail/goods'
import {dotData, copy, confirm, handleJsonStringArr, alert} from '@/utils'
import {unixTimestampFilter, decimalNumFilter, hasOperation} from '@/filters'
import {isFormatNumber, range} from '@/utils/validate'
import {payFhbTypes} from '@/utils/selectOptions'
import {mapGetters} from 'vuex'
const flag = true // 邓下午：权限配置
export default {
  name: 'myordersPaymentAdditional',
  components: {
    paymentHeader,
    goods
  },
  data() {
    return {
      id: this.$route.params.id,
      bid: this.$route.query.bid,
      totalMoney: 0,
      orderDetail: {},
      fhbOrder: {},
      fhbOrderGoods: {},
      fhbOrderConsigneeInfo: {},
      fhbOrderBiddingLogs: [],
      fhbOrderBiddingLog: {},
      fhbOrderPickupInfo: {},
      paymentTypes: [],
      model: {
        paymentType: ''
      },
      htmltext: '',
      routeName: this.$route.name,
      routeNextPath: '',
      paymentState: false,
      payDialog: false,
      disabledBtn: false,
      form: {
        additionalName: '',
        additionalMoney: '',
        additionalMemo: ''
      },
      rules: {
        additionalName: [
          {required: true, message: '请输入费用名称', trigger: 'blur'},
          {max: 10, message: '最多十个字符', trigger: 'blur'}
        ],
        additionalMoney: [
          {required: true, message: '请输入追加金额', trigger: 'blur'},
          { validator: isFormatNumber, int: 7, decimal: 2, message: '输入8位以下整数或2位小数', trigger: 'blur' }
        ],
        additionalMemo: [
          {validator: range, max: 80, isString: true, message: '备注最多80字', trigger: 'blur'}
        ]
      },
      confirmHtml: {},
      confirmPayDialog: false,
      timer: 3000,
      balance: 0,
      showWalletPay: false,
      walletPwd: '',
      error_message: '',
      cantWalletPay: false,
      loading: false
    }
  },
  filters: {
    unixTimestampFilter,
    decimalNumFilter
  },
  watch: {
    'walletPwd'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.error_message = ''
      if (this.loadding) {
        this.loadding = false
      }
    },
    'form.additionalMoney'(val, oldVal) {
      if (val === oldVal) {
        return
      }
      // if (val && (this.balance < parseFloat(this.form.additionalMoney) || parseFloat(this.form.additionalMoney) <= 0)) {
      if (val && (this.balance < parseFloat(this.form.additionalMoney))) {
        this.cantWalletPay = true
        this.model.paymentType = '1'
      } else {
        this.cantWalletPay = false
      }
      if (parseFloat(this.form.additionalMoney) === 0) {
        this.model.paymentType = '3'
      }
    }
  },
  computed: {
    carContent() {
      if (this.fhbOrderBiddingLog.carsHold) {
        return '配送车辆：' + this.fhbOrderBiddingLog.cars + '辆'
      } else {
        return '配送车辆：0辆'
      }
    },
    areaNum() {
      return dotData(this.fhbOrderBiddingLog, 'area') || 0
    },
    areaContent() {
      return '仓库：' + this.areaNum + '㎡'
    },
    computedPaymentTypes() {
      return this.paymentTypes.filter(v => { // 邓下午：权限配置
        if (flag) {
          return flag
        }
        let prefix = ''
        switch (this.routeName) {
          case 'myOrdersConfirmingPaymentAdditional': prefix = 'confirming'
            break
          case 'myOrdersInservicePaymentAdditional': prefix = 'in-service'
            break
        }
        if (!prefix) {
          return false
        }
        if (hasOperation(prefix + '-pay-1') && v.value === '1') { // 服务中支付宝 service|700-pay-1
          return true
        }
        if (hasOperation(prefix + '-pay-2') && v.value === '2') { // 服务中微信 service|700-pay-2
          return true
        }
        if (hasOperation(prefix + '-pay-auditPay')) { // 服务中出纳支付 service|700-pay-auditPay
          return true
        }
        if (hasOperation(prefix + '-pay-3') && v.value === '3') { // 服务中钱包余额 service|700-pay-3
          return true
        }
        return false
      }).map(v => { // 权限配置之后再开始 页面功能
        // 余额为零 禁用 支付宝微信
        if (this.form.additionalMoney === 0) {
          if (['1', '2'].indexOf(v.value) >= 0) {
            v.disabled = true
          }
        }
        // 余额不足 禁用钱包余额
        if (this.cantWalletPay) {
          if (v.value === '3') {
            v.disabled = true
          }
        }

        // 运营后台配置禁用支付宝
        if (this.GET_GLOBAL_CONFIG('aliPayPC') === false) {
          console.log('aliPayPC', v.value)
          if (v.value === '1') {
            v.disabled = true
            v.tip = '维护中请稍后再试'
          }
        }
        // 运营后台配置禁用微信
        if (this.GET_GLOBAL_CONFIG('weChatPayPC') === false) {
          if (v.value === '2') {
            v.disabled = true
            v.tip = '维护中请稍后再试'
          }
        }
        // 运营后台配置禁用钱包余额
        if (this.GET_GLOBAL_CONFIG('walletPC') === false) {
          if (v.value === '3') {
            v.disabled = true
            v.tip = '维护中请稍后再试'
          }
        }
        return v
      })
    },
    ...mapGetters(['GET_GLOBAL_CONFIG'])
  },
  created() {
    if (this.routeName === 'myOrdersInservicePaymentAdditional') {
      this.routeNextPath = '/ss-fhb/myOrders/inService/index'
    } else {
      this.routeNextPath = '/ss-fhb/myOrders/confirming/index'
    }
    this.createPaymentTypes()
    this.$ajax.get('/ms-fahuobao-order/FhbOrder/findFhbOrderParticulars', {orderId: this.id}).then(response => {
      if (response) {
        this.orderDetail = response.data
        this.fhbOrder = this.orderDetail.fhbOrder || {}
        this.fhbOrderConsigneeInfo = this.orderDetail.fhbOrderConsigneeInfo || {}
        if (Array.isArray(this.orderDetail.fhbOrderGoods)) {
          this.orderDetail.fhbOrderGoods.forEach(item => {
            item.picture = handleJsonStringArr(item.picture)
          })
        }
        this.fhbOrderGoods = this.orderDetail.fhbOrderGoods || []
        this.fhbOrderBiddingLog = this.orderDetail.fhbOrderBiddingLog || {}
        this.fhbOrderBiddingLogs = this.orderDetail.fhbOrderBiddingLogs || []
        this.fhbOrderPickupInfo = this.orderDetail.fhbOrderPickupInfo || {}
      }
    })
    // 获取钱包余额
    // 获取钱包余额
    this.$ajax.get('/ms-user-wallet/wallet/home-page').then(response => {
      let success = dotData(response, 'success')
      if (success) {
        this.balance = dotData(response, 'data.balance')
      }
    })
  },
  methods: {
    handleJsonStringArr,
    createPaymentTypes() {
      payFhbTypes().then(arr => {
        this.paymentTypes = arr
      })
    },
    payment($event) {
      if (!this.model.paymentType) {
        alert('请选择支付方式')
      } else {
        // 钱包余额支付
        if (this.model.paymentType === '3') {
          this.confirmPayDialog = false
          this.showWalletPay = true
          this.walletPwd = ''
        } else {
          const newTab = window.open('/static/pay.html')
          // let _this = this
          this.confirmPayDialog = false
          let data = copy(this.form, true)
          data.orderId = this.id
          data.payType = this.model.paymentType
          this.$ajax.post('/ms-fahuobao-order/FhbAdditional/saveAdditionalFee', data).then(response => {
            const success = dotData(response, 'success')
            if (success) {
              let temp = `<!DOCTYPE html>
              <html lang="en">
              <head>
                  <meta charset="UTF-8">
                  <title>Title</title>
              </head>
              <body>
              ${response.data.sHtmlText}
              </body>
              </html>
              `
              newTab.document.write(temp)
              newTab.focus()
              this.payDialog = true
              this.disabledBtn = false
              if (this.model.paymentType === 'auditPay') {
                this.payDialog = false
                this.disabledBtn = false
                newTab.close()
                confirm('出纳支付成功，请进入支付管理界面查看支付信息', '提示', {
                  type: 'success'
                }).finally(_ => {
                  this.btnDialog() // 刷新页面到父页面
                })
              }
            } else {
              newTab.close()
              this.unsuccessful()
            }
          }).catch(() => {
            newTab.close()
            this.unsuccessful()
          })
        }
      }
    },
    // 余额支付
    walletpay() {
      this.loading = true
      let data = copy(this.form, true)
      data.orderId = this.id
      data.password = this.walletPwd
      this.$ajax.post('/ms-user-wallet/wallet/addfee-balance-pay', data).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          confirm('支付成功', '提示', {
            type: 'success'
          }).finally(_ => {
            this.btnDialog() // 刷新页面到父页面
          })
          this.showWalletPay = false
          this.walletPwd = ''
        } else {
          this.error_message = dotData(response, 'error')
        }
        this.loading = false
      })
    },
    paymentDialog() {
      this.confirmHtml.orderNo = this.fhbOrder.orderNo
      this.confirmHtml.service = this.fhbOrder.service
      this.confirmHtml.consigneName = this.fhbOrderConsigneeInfo.consigneName
      this.confirmHtml.consignePhone = this.fhbOrderConsigneeInfo.consignePhone
      this.confirmHtml.name = this.fhbOrderBiddingLog.name
      this.confirmHtml.additionalName = this.form.additionalName
      this.confirmHtml.additionalMoney = this.form.additionalMoney
      this.confirmHtml.additionalMemo = this.form.additionalMemo
      this.$refs.form.validate().then((result) => {
        if (result) {
          if (this.model.paymentType) {
            this.confirmPayDialog = true
          } else {
            alert('请选择支付方式')
          }
        }
      })
    },
    goPay() {
      this.$nextTick(_ => {
        document.getElementById('submit').submit()
        this.payDialog = true
        this.disabledBtn = false
      })
    },
    successful() {
      // this.disabledBtn = true
      this.$ajax.get('/ms-fahuobao-order/FhbAdditional/findAddtionalStatus', {orderId: this.id}).then(response => {
        const success = response
        if (success) {
          this.paymentState = true
          this.payDialog = false
          setTimeout(() => {
            this.btnDialog() // 刷新页面到父页面
          }, 3000)
        } else {
          this.disabledBtn = true
        }
      })
    },
    btnDialog() {
      this.paymentState = false
      // this.setCloseRoute({path: this.$route.fullPath})
      // this.setRefreshRoute({path: this.routeNextPath})
      this.$router.push({path: '/redirect' + this.routeNextPath})
    },
    unsuccessful() {
      this.payDialog = false
      this.$confirm('很抱歉！支付失败。您可以尝试重新支付或联系客服。', '温馨提示', {
        confirmButtonText: '重新支付',
        cancelButtonText: '联系客服',
        closeOnClickModal: false,
        type: 'warning',
        center: true
      }).then(() => {
        // 重新支付
        // this.goPay()
        this.payment()
      }).catch(() => {
        // 联系客服
      })
    },
    pledge() {
      this.BighomeServiceCommitment = this.fhbOrderBiddingLog.bighomeServiceCommitment
      console.log(this.fhbOrderBiddingLog, 'this.BighomeServiceCommitment')
      let pledgeStr = `<p>1.` + this.BighomeServiceCommitment.carrSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.freeForCarry + `</p>
                       <p>2.` + this.BighomeServiceCommitment.overmileSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.coastForOvermile + `</p>
                       <p>3.` + this.BighomeServiceCommitment.storageSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.freeForStorage + `</p>
                       <p>4.` + this.BighomeServiceCommitment.uniformSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.serviceOnUniform + `</p>
                       <p>5.` + this.BighomeServiceCommitment.basicSubject + `</p>
                       <p>&nbsp;&nbsp;&nbsp;` + this.BighomeServiceCommitment.basicCommitment + `</p>`
      this.$alert(pledgeStr, '师傅服务承诺', {
        showConfirmButton: '关闭',
        dangerouslyUseHTMLString: true
      })
    }
  }
}
</script>

<style>
  .fontsize-sm {
    font-size: 8px;
  }
</style>
